<template>
  <div>
    <!-- 日期选择 -->
    <div class="min-w-[540px] ">
      <el-form class="flex flex-wrap  lg:justify-start sm:justify-center py-4 pl-4 bg-white border border-sky-100">
        <el-form-item label="wiki名称">
          <el-input v-model="searchWikiName" placeholder="请输入" style="width: 200px;" />
        </el-form-item>
        <el-form-item label="创建日期" class="ml-4">
          <!-- 日期选择组件（区间选择） -->
          <el-date-picker v-model="pickDate" @change="datepickerChange" :shortcuts="shortcuts" type="daterange"
            range-separator="至" start-placeholder="Start Time" end-placeholder="End Time" size="default" />
        </el-form-item>
        <el-button type="primary" :icon="Search" class="ml-4" @click="onSubmit">查询</el-button>
        <el-button class="ml-4" :icon="RefreshRight" @click="onReset">重置</el-button>
      </el-form>
    </div>
    <!-- Wiki列表 -->
    <div class="mt-4 bg-white border border-sky-100 pt-4 min-w-[540px]">
      <!-- 新增按钮 -->
      <div class="mb-4 pl-4">
        <el-button type="primary" @click="showAddWikiDialog">
          <el-icon class="mr-1">
            <Plus />
          </el-icon>
          新增Wiki</el-button>
      </div>
      <!-- 表格 -->
      <el-table class="ml-4" :data="tableData" border stripe style="width: 90%; min-width: 520px;" max-height="550"
        v-loading="tableLoading">
        <!-- <el-table-column prop="id" label="序号" width="80" /> -->
        <el-table-column prop="title" label="Wiki标题" width="180">
          <template #default="scope">
            <el-popover effect="light" trigger="hover" placement="top" width="auto">
              <template #default>
                <div>{{ scope.row.title }}</div>
              </template>
              <template #reference>
                <el-tag type="success">{{ scope.row.title }}</el-tag>
              </template>
            </el-popover>
          </template>
        </el-table-column>
        <el-table-column prop="cover" label="封面" width="175">
          <template #default="scope">
            <el-image style="width: 100px; height: 70px;" fit="cover" :src="scope.row.cover" />
          </template>
        </el-table-column>
        <el-table-column prop="isTop" label="是否置顶" width="120">
          <template #default="scope">
            <el-switch v-model="scope.row.isTop" @change="handleIsTopChange(scope.row)" inline-prompt
              :active-icon="Check" :inactive-icon="Close" />
          </template>
        </el-table-column>
        <el-table-column prop="isPublish" label="是否发布" width="120">
          <template #default="scope">
            <el-switch v-model="scope.row.isPublish" @change="handleIsPublishChange(scope.row)" inline-prompt
              :active-icon="Check" :inactive-icon="Close" />
          </template>
        </el-table-column>
        <el-table-column prop="createTime" label="创建时间" width="180" />

        <el-table-column fixed="right" label="操作">
          <template #default="scope">
            <el-tooltip class="box-item" effect="dark" content="编辑" placement="bottom">
              <el-button @click="editWiki(scope.row)" type="primary" size="small" :icon="Edit" circle>
              </el-button>
            </el-tooltip>

            <el-tooltip class="box-item" effect="dark" content="编辑目录" placement="bottom">
              <el-button @click="handleEditCatalog(scope.row)" type="" size="small" :icon="Tickets" circle>
              </el-button>
            </el-tooltip>

            <el-tooltip class="box-item" effect="dark" content="预览" placement="bottom">
              <el-button size="small" :icon="View" circle>
              </el-button>
            </el-tooltip>

            <el-tooltip class="box-item" effect="dark" content="删除" placement="bottom">
              <el-button @click="handleDelete(scope.row.id)" type="danger" size="small" :icon="Delete" circle>
              </el-button>
            </el-tooltip>

          </template>
        </el-table-column>

      </el-table>

      <!-- 分页组件 -->
      <div class="mt-10 mb-4 flex justify-center w-full">
        <el-pagination v-model:current-page="current" v-model:page-size="size" :page-sizes="[5, 10, 20]"
          @size-change="pageSizeChange" @current-change="currentPageChange" :small="false" :background="true"
          layout="total, sizes, prev, pager, next, jumper" :total="total" class="" />
      </div>
    </div>


    <!-- 新增Wiki对话框 -->
    <FormDialog ref="formDialogRef" title="新增Wiki" @submit="submitAdd" @cancle="handleCancle" confirm-text="新增">
      <el-form ref="formRef" :rules="rules" :model="AddWikiFormValue">
        <el-form-item prop="title" label="Title" label-width="80px" size="default">
          <el-input v-model="AddWikiFormValue.title" maxlength="20" show-word-limit clearable placeholder="请输入标题" />
        </el-form-item>
        <el-form-item prop="cover" label="Cover" label-width="80px" size="default">
          <el-upload class="avatar-uploader" action="#" :on-change="handleCoverChange" :auto-upload="false"
            :show-file-list="false">
            <img v-if="AddWikiFormValue.cover" :src="AddWikiFormValue.cover" class="avatar" />
            <el-icon v-else class="avatar-uploader-icon">
              <Plus />
            </el-icon>
          </el-upload>
        </el-form-item>
        <el-form-item prop="summary" label="Summary:" label-width="80px" size="default">
          <el-input v-model="AddWikiFormValue.summary" type="textarea" />
        </el-form-item>
      </el-form>
    </FormDialog>

    <!-- 修改Wiki对话框 -->
    <FormDialog ref="editFormDialogRef" title="编辑Wiki" @submit="submitEdit" @cancle="handleCancle" confirm-text="保存">
      <el-form ref="editFormRef" :rules="rules" :model="editWikiFormValue">
        <el-form-item prop="title" label="Title" label-width="80px" size="default">
          <el-input v-model="editWikiFormValue.title" maxlength="20" show-word-limit clearable placeholder="请输入标题" />
        </el-form-item>
        <el-form-item prop="cover" label="Cover" label-width="80px" size="default">
          <el-upload class="avatar-uploader" action="#" :on-change="handleEditCoverChange" :auto-upload="false"
            :show-file-list="false">
            <img v-if="editWikiFormValue.cover" :src="editWikiFormValue.cover" class="avatar" />
            <el-icon v-else class="avatar-uploader-icon">
              <Plus />
            </el-icon>
          </el-upload>
        </el-form-item>
        <el-form-item prop="summary" label="Summary:" label-width="80px" size="default">
          <el-input v-model="editWikiFormValue.summary" type="textarea" />
        </el-form-item>
      </el-form>
    </FormDialog>


    <!-- 目录Dialog -->
    <WikiCatalogEditDialog ref="editCatalogDialogRef" :title="title">
      
    </WikiCatalogEditDialog>

  </div>
</template>

<script setup>
import { reactive, ref, onMounted, watch } from 'vue';
import moment from 'moment';
import { addWiki, deleteWiki, getWikiPageList, updateIsPublish, updateIsTop, updateWiki } from '@/api/admin/wiki';
import { Search, Close, Check, RefreshRight, Edit, Tickets, View, Delete } from '@element-plus/icons-vue'
import FormDialog from '@/components/FormDialog.vue';
import { uploadFile } from '@/api/admin/file';
import { showConfirm, showMessage } from '@/composables/utils';
import WikiCatalogEditDialog from '@/components/WikiCatalogEditDialog.vue';


//====================== 日期选择事件 ======================
const startDate = reactive({})
const endDate = reactive({})
const datepickerChange = (e) => {
  startDate.value = moment(e[0]).format('YYYY-MM-DD')
  endDate.value = moment(e[1]).format('YYYY-MM-DD')
  console.log('startTime:' + startDate.value + 'endTime:' + endDate.value)
}
//日期shotscut
const shortcuts = [
  {
    text: 'Today',
    value: new Date(),
  },
  {
    text: 'Yesterday',
    value: () => {
      const end = new Date();
      const start = new Date();
      start.setTime(start.getTime() - 3600 * 1000 * 24);
      return [start, end];
    },
  },
  {
    text: 'A week ago',
    value: () => {
      const end = new Date();
      const start = new Date();
      start.setTime(start.getTime() - 3600 * 1000 * 24 * 7);
      return [start, end];
    },
  },
];

//=======================查询知识库=======================
const tableData = ref([]) //展示集合
const pickDate = ref('')
const searchWikiName = ref('')  // 模糊搜索wiki名称
const tableLoading = ref(false)
const current = ref(1)
const total = ref(0)
const size = ref(10)
const onSubmit = () => {
  tableLoading.value = true
  getWikiPageList({
    current: current.value,
    size: size.value,
    startDate: startDate.value,
    endDate: endDate.value,
    title: searchWikiName.value
  }).then(res => {
    if (res.success) {
      tableData.value = res.data
      total.value = res.total
      current.value = res.current
      size.value = res.size
    }
  }).finally(() => {
    tableLoading.value = false
  })
}
onSubmit()



const pageSizeChange = (val) => {  // 每页展示大小
  console.log("当前页码大小: " + val)
  size.value = val
  onSubmit()
}
const currentPageChange = (val) => { //
  console.log("当前页码: " + val)
  current.value = val
  onSubmit()
}


//=======================新增Wiki=======================
const formRef = ref(null)
const formDialogRef = ref(null)
const AddWikiFormValue = reactive({
  title: '',
  cover: '',
  summary: ''
})
const rules = reactive({
  title: [
    { required: true, message: '请输入标题', trigger: 'blur' },
    { min: 1, max: 20, message: '标题要求大于1个字符，小于20个字符', trigger: 'blur' },
  ],
  summary: [
    { required: true, message: '请输入摘要', trigger: 'blur' },
    { min: 1, max: 40, message: '摘要要求大于1个字符，小于40个字符', trigger: 'blur' },
  ],
  cover: [{ required: true, message: '请上传封面', trigger: 'blur' }],
})
const showAddWikiDialog = () => { // 打开新增对话框
  formDialogRef.value.showDialog()
}
const submitAdd = () => {   // 提交新增
  formRef.value.validate((valid) => {
    if (!valid) {
      showMessage('表单校验失败', 'error')
      return
    }
    addWiki(AddWikiFormValue).then(res => {
      if (!res.success) {
        showMessage(res.message, 'error')
        return
      }
      showMessage('新增成功', 'success')
      formDialogRef.value.closeDialog()
      onSubmit()
      AddWikiFormValue.title = ''
      AddWikiFormValue.cover = ''
      AddWikiFormValue.summary = ''
    })
  })
}
const handleCoverChange = (file) => {  // 上传封面
  let formData = new FormData()
  formData.append('file', file.raw)
  uploadFile(formData).then(res => {
    if (!res.success) {
      showMessage(res.message, 'error')
      return
    }
    AddWikiFormValue.cover = res.data.url
    showMessage('上传成功!', 'success')
  })
}




//=======================修改Wiki=======================
const editFormDialogRef = ref(null)
const editFormRef = ref(null)
const editWikiFormValue = reactive({
  id: '',
  title: '',
  cover: '',
  summary: ''
})
const editWiki = (row) => {
  editWikiFormValue.id = row.id
  editWikiFormValue.title = row.title
  editWikiFormValue.cover = row.cover
  editWikiFormValue.summary = row.summary
  editFormDialogRef.value.showDialog()
}
const submitEdit = () => {    // 提交修改
  editFormRef.value.validate((valid) => {
    if (!valid) {
      showMessage('表单校验失败', 'error')
      return
    }
    updateWiki(editWikiFormValue).then(res => {
      if (!res.success) {
        showMessage(res.message, 'error')
        return
      }
      showMessage('修改成功', 'success')
      editFormDialogRef.value.closeDialog()
      onSubmit()
      editWikiFormValue.title = ''
      editWikiFormValue.cover = ''
      editWikiFormValue.summary = ''
    })
  })
}
const handleEditCoverChange = (file) => {   // 上传封面
  let formData = new FormData()
  formData.append('file', file.raw)
  uploadFile(formData).then(res => {
    if (!res.success) {
      showMessage(res.message, 'error')
      return
    }
    editWikiFormValue.cover = res.data.url
    showMessage('上传成功!', 'success')
  })
}

//=======================修改置顶/发布状态=======================
const handleIsTopChange = (row) => {
  updateIsTop({ id: row.id, isTop: row.isTop }).then(res => {
    onSubmit()// 重新渲染
    if (!res.success) {
      showMessage(res.message, 'error')
      return
    }
    showMessage(row.isTop ? '置顶成功' : '取消置顶成功', 'success')
  })
}
const handleIsPublishChange = (row) => {
  updateIsPublish({ id: row.id, isPublish: row.isPublish }).then(res => {
    onSubmit()// 重新渲染
    if (!res.success) {
      showMessage(res.message, 'error')
      return
    }
    showMessage(row.isPublish ? '发布成功' : '取消发布成功', 'success')
  })
}

//=======================删除Wiki=======================
const handleDelete = (id) => {
  showConfirm('确定删除这篇Wiki吗').then(() => {
    deleteWiki(id).then(res => {
      if (!res.success) {
        showMessage(res.message, 'error')
        return
      }
      onSubmit()// 重新渲染
      showMessage('删除成功', 'success')
    })
  }).catch(() => {
    showMessage('取消删除', 'info')
  })
}


//========================编辑Wiki目录======================
const editCatalogDialogRef = ref(null)
const title = ref('')
const handleEditCatalog = (row) => {
  title.value = '编辑目录 --- ' + row.title
  editCatalogDialogRef.value.open(row.id)
}


















//=======================重置查询条件=======================
const onReset = () => {
  searchWikiName.value = ''
  pickDate.value = ''
  startDate.value = ''
  endDate.value = ''
  size.value = 5
  current.value = 1
}
const handleCancle = () => {}



</script>

<style scoped>
.el-icon.avatar-uploader-icon {
  font-size: 28px;
  color: #8c939d;
  width: 200px;
  height: 100px;
  text-align: center;
}

.avatar-uploader .avatar {
  width: 250px;
  height: 160px;
  display: block;
  object-fit: cover;
}
</style>

<style>
.el-textarea__inner:focus {
  outline: 0 !important;
  box-shadow: 0 0 0 1px var(--el-input-focus-border-color) inset !important;
}
</style>